<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.orderCode" clearable :placeholder="$t('order.orderCode')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.typeNo" clearable :placeholder="$t('order.typeNo')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="listQuery.startTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('common.startDate')" class="filter-item" />
      <el-date-picker v-model="listQuery.endTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('common.endDate')" class="filter-item" />
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('common.export') }}
      </el-button>
      <el-checkbox v-model="checked" style="margin-left: 10px;" size="medium">
        {{ $t('common.openAll') }}
      </el-checkbox>
    </div>
    <!-- 主界面数据 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      :row-style="{height:'20px'}"
      :cell-style="{padding:'2px'}"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column :label="$t('order.orderCode')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('order.orderName')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('order.orderStatus')" width="120px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="orderStatus[row.orderStatus].color">{{ orderStatus[row.orderStatus].label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('order.orderUnit')" width="*" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('order.orderNumber')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('order.actualNumber')" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.actualNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('order.actualStart')" width="220px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.actualStart }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('order.actualEnd')" width="220px" align="center">
        <template slot-scope="{row}">
          <span type="time">{{ row.actualEnd }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.lineNumber')" width="*" align="center">
        <template slot-scope="{row}">
          <span>{{ row.lineNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('produce.typeNo')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.typeNo }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.manager')" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.manager }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('produce.creatTime')" width="220px" align="center">
        <template slot-scope="{row}">
          <span type="time">{{ row.creatTime }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checked" :label="$t('order.productDescription')" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.matDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checked" :label="$t('order.picNumberVer')" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.matVer }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checked" :label="$t('order.bomCode')" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bomSetId }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checked" :label="$t('order.bomVer')" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bomSetVersion }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checked" :label="$t('order.processRoute')" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.processingNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checked" :label="$t('order.processRouteVer')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.processingVer }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checked" :label="$t('order.sceneCode')" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.cjcode }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checked" :label="$t('order.customerOrderNo')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.cusSo }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checked" :label="$t('order.customerOrderLine')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.cusSoItem }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checked" :label="$t('order.productDepartment')" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.ownerCode }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <div>
      <gant-chart :title="$t('order.orderGantActual')" :chart-data="gantData" />
    </div>
  </div>
</template>

<script>
import { getOrderHistory } from '@/api/order'
import { getLineList } from '@/api/equipment'
import { getTypeList } from '@/api/produce'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import GantChart from '@/components/Charts/GantChart' // secondary package based on el-pagination
import i18n from '@/lang'

export default {
  name: 'OrderSummary',
  components: {
    Pagination,
    GantChart },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      checked: false,
      editRight: true,
      tableKey: 0,
      list: [],
      lineOptions: [],
      typeOptions: [],
      gantData: {
        valueY: [],
        start: [],
        end: [],
        label: [] },
      // 任务u状态
      orderStatus: [
        { label: '已下达', key: 'REL', color: 'info' },
        { label: '生产中', key: 'RUNNING', color: 'warning' },
        { label: '已完成', key: 'FINISHED', color: 'success' },
        { label: '已锁定', key: 'LOCKED', color: 'danger' },
        { label: '已取消', key: 'CANCELED', color: 'danger' },
        { label: '已关闭', key: 'CLOSED', color: 'danger' }],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        orderCode: '',
        typeNo: '',
        lineNumber: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+due_date'
      },
      showReviewer: false,
      temp: {
        orderId: 0,
        orderCode: '',
        orderName: '',
        orderStatus: 0,
        orderUnit: '',
        actualStart: Date.now(),
        actualEnd: Date.now(),
        lineNumber: '',
        typeNo: '',
        creatTime: Date.now(),
        manager: '',
        orderNumber: 0,
        matDesc: '',
        matVer: 0,
        actualNumber: 0,
        bomSetId: '',
        bomSetVersion: 0,
        processingNumber: '',
        processingVer: 0,
        cjcode: '',
        cusSo: '',
        cusSoItem: '',
        ownerCode: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        lineName: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        lineNumber: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        priority: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      },
      downloadLoading: false,
      searchLoading: {
        company: false,
        manager: false
      },
      searchDialogStatus: '',
      searchDialogFormVisible: {
        company: false,
        manager: false
      }
    }
  },
  created() {
    this.listQuery.lineNumber = this.$store.getters.lineNumber
    this.getLineList()
    this.getList()
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
  },
  methods: {
    formatDateTime(date) {
      return date.substring(0, 10)
    },
    // 获取甘特图数据
    getGantData() {
      this.gantData.valueY = []
      this.gantData.start = []
      this.gantData.end = []
      this.gantData.label = []
      this.list.forEach(item => {
        this.gantData.valueY.push(item.orderCode)
        this.gantData.start.push(item.actualStart)
        this.gantData.end.push(item.actualEnd)
        this.gantData.label.push(this.orderNumber)
      })
    },
    // 获取清单
    getList() {
      this.listLoading = true
      getOrderHistory(this.listQuery).then(response => {
        this.list = response.data.orderHistory
        this.total = response.data.total
        this.listLoading = false
        this.getGantData()
      })
    },
    handleLineSelect() {
      this.listQuery.lineNumber = this.temp.lineNumber
      this.typeOptions = []
      getTypeList(this.listQuery).then(response => {
        this.typeOptions = response.data.types
        this.listQuery.lineNumber = ''
      })
    },
    // 获取线体清单
    getLineList() {
      this.listLoading = true
      getLineList(this.listQuery).then(response => {
        this.lineOptions = response.data.lines
        this.listLoading = false
      })
    },
    // 获取线体清单
    getTypeList() {
      this.listLoading = true
      getTypeList(this.listQuery).then(response => {
        this.lineOptions = response.data.lines
        this.listLoading = false
      })
    },
    // 查看错误信息
    handleCheck(row) {
      const ret = Object.assign({}, row) // copy obj
      if (ret.errMsg === null | '') {
        return
      }
      this.$msgbox({
        message: ret.errMsg,
        type: 'error'
      })
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 排序时调用
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'startDate') {
        this.sortByCreatTime(order)
      } else if (prop === 'dueDate') {
        this.sortBydueDate(order)
      } else if (prop === 'priority') {
        this.sortByPriority(order)
      }
    },
    // 根据创建时间排序
    sortByCreatTime(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+start_date'
      } else {
        this.listQuery.sort = '-start_date'
      }
      this.handleFilter()
    },
    // 根据交期排序
    sortBydueDate(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+due_date'
      } else {
        this.listQuery.sort = '-due_date'
      }
      this.handleFilter()
    },
    // 根据优先级
    sortByPriority(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+priority'
      } else {
        this.listQuery.sort = '-priority'
      }
      this.handleFilter()
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          i18n.t('order.orderCode'),
          i18n.t('order.orderName'),
          i18n.t('order.orderStatus'),
          i18n.t('order.orderUnit'),
          i18n.t('order.orderNumber'),
          i18n.t('order.actualNumber'),
          i18n.t('order.actualStart'),
          i18n.t('order.actualEnd'),
          i18n.t('equipment.lineNumber'),
          i18n.t('produce.typeNo'),
          i18n.t('equipment.manager'),
          i18n.t('produce.creatTime'),
          i18n.t('order.productDescription'),
          i18n.t('order.picNumberVer'),
          i18n.t('order.bomCode'),
          i18n.t('order.bomVer'),
          i18n.t('order.processRoute'),
          i18n.t('order.processRouteVer'),
          i18n.t('order.sceneCode'),
          i18n.t('order.customerOrderNo'),
          i18n.t('order.customerOrderLine'),
          i18n.t('order.productDepartment')]
        const filterVal = ['orderCode', 'orderName', 'orderStatus', 'orderUnit', 'orderNumber', 'actualNumber',
          'actualStart', 'actualEnd', 'lineNumber', 'typeNo', 'manager', 'creatTime', 'productDescription', 'picNumberVer', 'bomCode', 'bomVer', 'processRoute', 'processRouteVer', 'sceneCode', 'customerOrderNo', 'customerOrderLine', 'productDepartment']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '产品清单'
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
